# -*- coding: utf-8 -*-
# @Author: Anderson
# @Date:   2019-10-30 14:18:42
# @Last Modified by:   Anderson
# @Last Modified time: 2019-10-30 16:03:55

import ctypes
import time


class WechatBot(object):

	def __init__(self):
		self.RECVTEXTMSG_CALLBACK = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_wchar_p, ctypes.c_wchar_p)
		self.sdk = ctypes.CDLL("WeChatSDK.dll")
		self.running = False
		self.user_msg_handler = None
		self.__msg_callback = None

	def login(self):
		self.pid = self.sdk.WXOpenWechat()
		input('完成登录后请输入回车>')
		return self.pid

	def check_bot_status(self):
		if self.sdk.WXIsWechatAlive(self.pid) == 1 and self.sdk.WXIsWechatSDKOk(self.pid) == 0:
			return True
		else:
			return False

	def initialize(self):
		if self.check_bot_status():
			self.sdk.WXInitialize(self.pid)
			time.sleep(1)
			self.running = True
			self.__msg_callback = self.RECVTEXTMSG_CALLBACK(self.msg_handler_wrap)
			self.sdk.WXRecvTextMsg(self.pid, self.__msg_callback)
			return True
		else:
			return False

	def send(self, wxid, msg):
		self.sdk.WXSendTextMsg(self.pid, wxid, str(msg))

	def set_msg_handler(self, func):
		self.msg_handler = func

	def msg_handler_wrap(self, pid, wxid, msg):
		self.msg_handler(pid, wxid, msg)
		return 0

	def run(self):
		while self.running:
			pass
